package com.tuanzi.loan.business.service.galaxycard.impl;

import com.tuanzi.loan.business.constants.galaxycard.PrivilgeStatusConst;
import com.tuanzi.loan.business.entity.galaxycard.*;
import com.tuanzi.loan.business.repository.galaxycard.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tuanzi.loan.core.aspect.Debug;

import com.tuanzi.loan.business.service.galaxycard.GalaxyCardUserPrivilegeService;
import com.tuanzi.loan.vo.request.galaxycard.GalaxyCardUserPrivilegeSearchRequest;
import com.tuanzi.loan.vo.response.galaxycard.GalaxyCardUserPrivilegeSearchResponse;
import com.tuanzi.loan.core.vo.PageSearcher;
import org.springframework.data.domain.Page;

import javax.validation.constraints.Null;
import java.util.*;

/**
 * 银河黑卡用户权益 ServiceImplement
 * @author JinRuiyang 2018/1/9 14:56:20
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class GalaxyCardUserPrivilegeServiceImpl implements GalaxyCardUserPrivilegeService {
    @Autowired
    private GalaxyCardPrivilegeJpaRepository galaxyCardPrivilegeJpaRepository;
    @Autowired
    private GalaxyCardPrivilegeStatusJpaRepository galaxyCardPrivilegeStatusJpaRepository;
    @Autowired
    private GalaxyCardUserPrivilegeRepository galaxycarduserprivilegeRepository;
    @Autowired
    private GalaxyCardUserPrivilegeJpaRepository galaxycarduserprivilegeJpaRepository;
    @Autowired
    private GalaxyCardPrivilegeExpressJpaRepository galaxyCardPrivilegeExpressJpaRepository;
    @Autowired
    private GalaxyCardPrivilegeCDKeyJpaRepository galaxyCardPrivilegeCDKeyJpaRepository;

    private static Map<Long,List<GalaxyCardPrivilegeStatus>> cache;

    /**
     * 清空缓存
     */
    public static void cleanCache(){
        cache = null;
    }

    /**
     * 根据 权益 id 获取权益状态列表
     *
     * @param privilegeId 权益 id
     * @return 权益状态列表
     */
    @Override
    public List<GalaxyCardPrivilegeStatus> getStatusByPrivilegeId(Long privilegeId) {
        if (cache == null){
            cache = new HashMap<>();
            List<GalaxyCardPrivilegeStatus> statuses = galaxyCardPrivilegeStatusJpaRepository.findAll();
            for (GalaxyCardPrivilegeStatus status : statuses){
                List<GalaxyCardPrivilegeStatus> privilegeStatuses = cache.computeIfAbsent(status.getPrivilegeId(), k -> new ArrayList<>());
                privilegeStatuses.add(status);
            }
        }
        List<GalaxyCardPrivilegeStatus> result = cache.get(privilegeId);
        return result == null ? Collections.emptyList() : result;
    }

    /**
     * 获取权益列表
     *
     * @return 权益列表
     */
    @Override
    public List<GalaxyCardPrivilege> getPrivileges() {
        return galaxyCardPrivilegeJpaRepository.findAll();
    }

    /**
     * GalaxyCardUserPrivilege查询
     * @param pageSearcher 请求信息
     * @return 响应列表
     */
    public Page<GalaxyCardUserPrivilegeSearchResponse> list(PageSearcher<GalaxyCardUserPrivilegeSearchRequest> pageSearcher) {
        if (Objects.isNull(pageSearcher))
            throw new NullPointerException("pageSearcher is null");
        if (Objects.isNull(pageSearcher.getSearchCondition()) || Objects.isNull(pageSearcher.getPageable()))
            throw new NullPointerException("galaxyCardUserPrivilegeSearchRequest or pageable is null");
        return galaxycarduserprivilegeRepository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    /**
     * 根据id查找用户权益信息
     *
     * @return 用户权益信息id
     */
    @Override
    public GalaxyCardUserPrivilege findById(Long id) {
        if (Objects.isNull(id))
            throw new NullPointerException("user privilege id is null");
        return galaxycarduserprivilegeJpaRepository.findOne(id);
    }

    /**
     * 更新用户权益信息
     *
     * @param userPrivilege 用户权益信息
     */
    @Override
    public void update(GalaxyCardUserPrivilege userPrivilege) {
        galaxycarduserprivilegeJpaRepository.save(userPrivilege);
    }

    /**
     * 查询用户权益的快递信息
     *
     * @param id 主键
     * @return 快递信息
     */
    @Override
    public GalaxyCardPrivilegeExpress findExpressById(Long id) {
        return galaxyCardPrivilegeExpressJpaRepository.findOne(Objects.requireNonNull(id, "id is null"));
    }

    /**
     * 更新用户权益的快递信息
     *
     * @param express 更新快递信息
     */
    @Override
    public void update(GalaxyCardPrivilegeExpress express, GalaxyCardUserPrivilege userPrivilege) {
        express = Objects.requireNonNull(express);
        userPrivilege = Objects.requireNonNull(userPrivilege);
        if (Objects.isNull(userPrivilege.getExpressId()))
            throw new IllegalStateException("该用户未填写过快递信息");
        // 如果存在快递单号且状态为代发货 则 更新用户权益状态 为 已发货
        if (StringUtils.isNotBlank(express.getExpress_no())
                && userPrivilege.getPrivilegeStatus() == PrivilgeStatusConst.ACTIVING_WAIT_EXPRESS.val()){
            userPrivilege.setPrivilegeStatus(PrivilgeStatusConst.ACTIVING_EXPRESSING.val());
            galaxycarduserprivilegeJpaRepository.save(userPrivilege);
        }
        galaxyCardPrivilegeExpressJpaRepository.save(express);
    }

    /**
     * 添加用户权益的快递信息
     *
     * @param express 更新快递信息
     */
    @Override
    public void insert(GalaxyCardPrivilegeExpress express, GalaxyCardUserPrivilege userPrivilege) {
        express = Objects.requireNonNull(express);
        userPrivilege = Objects.requireNonNull(userPrivilege);
        if (Objects.nonNull(userPrivilege.getExpressId()))
            throw new IllegalStateException("该用户已经填写快递信息");
        galaxyCardPrivilegeExpressJpaRepository.save(Objects.requireNonNull(express));
        // 更新权益的快递单号
        userPrivilege.setExpressId(express.getId());
        galaxycarduserprivilegeJpaRepository.save(userPrivilege);
    }

    /**
     * 根据权益id获取该权益对应的所有激活码
     *
     * @param privilegeId 权益id
     * @return 激活码的 set 集合
     */
    @Override
    public Set<String> getPrivilegeCDKeyByPrivilegeId(Long privilegeId) {
        List<String> cdKeys = galaxycarduserprivilegeRepository.getPrivilegeCDKeyByPrivilegeId(privilegeId);
        return new HashSet<>(cdKeys);
    }

    /**
     * 添加权益激活码信息
     *
     * @param privilegeCDKey 权益激活码
     */
    @Override
    public void insert(GalaxyCardPrivilegeCDKey privilegeCDKey) {
        galaxyCardPrivilegeCDKeyJpaRepository.save(privilegeCDKey);
    }

    /**
     * 查询用户权益-激活码信息
     *
     * @param id 主键
     * @return 激活码信息
     */
    @Override
    public GalaxyCardPrivilegeCDKey findCDKeyById(Long id) {
        return galaxyCardPrivilegeCDKeyJpaRepository.findOne(Objects.requireNonNull(id));
    }
}